//
//  ScheduleRootViewController.m
//  YunDongGym
//
//  Created by lqq on 2018/8/3.
//  Copyright © 2018年 lqq. All rights reserved.
//


typedef NS_ENUM(NSInteger, CheckScheduleType) {
    CheckScheduleType_ByDay,//按天查看
    CheckScheduleType_ByWeek,//按周查看
};

#import "ScheduleRootViewController.h"
#import "DateCollectionCell.h"
#import "NSDate+DateTools.h"
#import "NSDate+Extension.h"
#import "YDChoiceDateAlertView.h"
#import "ScheduleDayController.h"
#import "YDSwitch.h"
#import "ScheduleWeekController.h"

@interface ScheduleRootViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,YDSwitchDelegate>

@property (nonatomic, strong) NSDate *selectDate;//当前日期
@property (nonatomic, assign) CheckScheduleType checkType;//查看类型

@property (nonatomic, strong) UILabel *titleLabel;//title日期label
@property (nonatomic, strong) UIButton *goTodayBtn;//返回今天btn
@property (nonatomic, strong) UICollectionView *dateCollectionView;//日历CollectionView
@property (nonatomic, strong) UIScrollView *contentScrollView;//内容区ScrollView

@property (nonatomic, strong) NSMutableArray *dateList;//日期数据源
@property (nonatomic, strong) NSArray *dateWeekDayList;//星期数据源
@property (nonatomic, strong) NSMutableArray *contentControllers;//内容区域控制器
@end

@implementation ScheduleRootViewController
{
    BOOL _layoutFinished;
}
#pragma mark Class Method
+ (instancetype)controller
{
    ScheduleRootViewController *vc = [[ScheduleRootViewController alloc] init];
    return vc;
}

#pragma mark Life Circle
- (void)viewDidLoad
{
    [super viewDidLoad];
    _contentControllers = [NSMutableArray array];
    _checkType = CheckScheduleType_ByDay;
    [self configUI];
    _dateWeekDayList = @[@"日",@"一",@"二",@"三",@"四",@"五",@"六"];
    _selectDate = [NSDate date];
}
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if (!_layoutFinished) {
        _layoutFinished = YES;
        [self updateContent];
    }
    
}
#pragma mark Config/UI
- (void)configUI{
    //titleView
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 105, 40)];
    UIImageView *titleDownImageView = [[UIImageView alloc] initWithImage:IMG_NAME(@"ic_down")];
    [titleView addSubview:titleDownImageView];
    [titleDownImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(titleView);
        make.height.equalTo(@(6));
        make.width.equalTo(@(10));
        make.centerY.equalTo(titleView);
    }];
    UITapGestureRecognizer *choiceDateTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(choiceDate)];
    [titleView addGestureRecognizer:choiceDateTap];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.frame = CGRectMake(0, 0, 95, 40);
    titleLabel.textColor = HEXColor(@"#0E1C29");
    titleLabel.font = MediumFont(17);
    
    [titleView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.centerY.equalTo(titleView);
        make.right.equalTo(titleDownImageView.mas_left).offset(-4);
        make.height.equalTo(@(40));
        
    }];
    
    
    _titleLabel = titleLabel;
    
    self.navigationItem.titleView = titleView;
    
    
    
    //日历view
    UIView *dateView = [[UIView alloc] init];
    dateView.layer.shadowColor = [UIColor blackColor].CGColor;
    dateView.layer.shadowOpacity = 0.15;
    dateView.layer.shadowRadius = 15;
    dateView.layer.shadowOffset = CGSizeMake(0, 0);
    dateView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:dateView];
    dateView.frame = CGRectMake(0, 0, kDeviceWidth, 70);
    UIView *goTodayView = [[UIView alloc] init];
    [dateView addSubview:goTodayView];
    goTodayView.frame = CGRectMake(0, 0, 45, dateView.height);
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = HEXColor(@"#DDDDDD");
    [goTodayView addSubview:lineView];
    lineView.frame = CGRectMake(0, 0, 1, 19);
    lineView.right = goTodayView.right;
    lineView.centerY = goTodayView.centerY;
    
    UIButton *goTodayBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [goTodayBtn setImage:[UIImage originImageWithImageName:@"btn_today_able"] forState:UIControlStateNormal];
    [goTodayBtn setImage:[UIImage originImageWithImageName:@"btn_today_disable"] forState:UIControlStateDisabled];
    [goTodayBtn addTarget:self action:@selector(goTodayBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    [goTodayView addSubview:goTodayBtn];
    goTodayBtn.frame = goTodayView.bounds;
    _goTodayBtn = goTodayBtn;

    //日历collectionView
    UICollectionViewFlowLayout *dateFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    dateFlowLayout.itemSize = CGSizeMake((kDeviceWidth - 46) / 7,70);
    dateFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    dateFlowLayout.minimumLineSpacing = 0.0;
    dateFlowLayout.minimumInteritemSpacing = 0.0;
    self.dateCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:dateFlowLayout];
    self.dateCollectionView.pagingEnabled = YES;
    self.dateCollectionView.showsHorizontalScrollIndicator = NO;
    self.dateCollectionView.showsVerticalScrollIndicator = NO;
    self.dateCollectionView.bounces = NO;
    self.dateCollectionView.dataSource = self;
    self.dateCollectionView.delegate = self;
    self.dateCollectionView.backgroundColor = [UIColor clearColor];
    [dateView addSubview:self.dateCollectionView];
    self.dateCollectionView.frame = CGRectMake(46, 0, dateView.width - 46, dateView.height);
    [self.dateCollectionView registerClass:[DateCollectionCell class] forCellWithReuseIdentifier:NSStringFromClass([DateCollectionCell class])];
    
    
    //ContentScrollView
    _contentScrollView = [[UIScrollView alloc] init];
    _contentScrollView.pagingEnabled = YES;
    _contentScrollView.showsHorizontalScrollIndicator = NO;
    _contentScrollView.showsVerticalScrollIndicator = NO;
    _contentScrollView.delegate = self;
    _contentScrollView.bounces = NO;
    _contentScrollView.backgroundColor = [UIColor redColor];
    _contentScrollView.contentSize = CGSizeMake(3*kDeviceWidth, 1);
    [self.view addSubview:_contentScrollView];
    _contentScrollView.frame = CGRectMake(0, dateView.bottom, kDeviceWidth, kDeviceHeight - dateView.height - [Toolkit getSystemNavHeight]);

    [self.view insertSubview:_contentScrollView atIndex:0];
    
    
    //选择日视图和周视图
    YDSwitch *viewSwitch = [[YDSwitch alloc] initWithFrame:CGRectMake(0, 0, 94, 30)];
    viewSwitch.titles = @[@"日",@"周"];
    viewSwitch.delegate = self;
//    viewSwitch.index = 1;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:viewSwitch];
    self.navigationItem.rightBarButtonItem = item;
}


- (void)updateContent
{
    _titleLabel.text = [Toolkit stringFromDate:_selectDate formatterString:@"yyyy年MM月"];
    if (_checkType == CheckScheduleType_ByDay) {
        _goTodayBtn.enabled = ![_selectDate isSameDay:[NSDate date]];
    } else {
        if ([[[NSDate date] getFirstAndLastDayOfThisWeek].firstObject isSameDay:[_selectDate getFirstAndLastDayOfThisWeek].firstObject]) {
            _goTodayBtn.enabled = NO;
        } else {
            _goTodayBtn.enabled = YES;
        }
    }
    
    self.dateList = [NSMutableArray array];
    NSInteger selectDayRow = 7+ _selectDate.weekday - 1;//选择日期的indexPath.row
    for (int i = 0 ; i < 24; i++) {
        NSDate *date = [_selectDate dateByAddingDays:(i-selectDayRow)];
        [self.dateList addObject:date];
        
    }

    [self.dateCollectionView reloadData];
    self.dateCollectionView.contentOffset = CGPointMake(self.dateCollectionView.frame.size.width, 0);
    
    self.contentScrollView.contentOffset = CGPointMake(self.contentScrollView.width, 0);
    
    BOOL find = NO;

    for (UIViewController *vc in self.contentControllers) {
        if (_checkType == CheckScheduleType_ByDay) {
            if ([vc isKindOfClass:[ScheduleDayController class]]) {
                ScheduleDayController *schduleDayVC = (ScheduleDayController *)vc;
                if ([schduleDayVC.date isSameDay:_selectDate]) {
                    [_contentScrollView addSubview:schduleDayVC.view];
                    schduleDayVC.view.left = kDeviceWidth;
                    find = YES;
                } else {
                    [vc.view removeFromSuperview];
                }
            } else {
                [vc.view removeFromSuperview];
            }
        } else {
            if ([vc isKindOfClass:[ScheduleWeekController class]]) {
                ScheduleWeekController *scheduleWeekVC = (ScheduleWeekController *)vc;
                if ([[scheduleWeekVC.date getFirstAndLastDayOfThisWeek].firstObject isSameDay:[_selectDate getFirstAndLastDayOfThisWeek].firstObject]) {//代表同一周
                    [_contentScrollView addSubview:scheduleWeekVC.view];
                    scheduleWeekVC.view.left = kDeviceWidth;
                    find = YES;
                } else {
                    [vc.view removeFromSuperview];
                }
            } else {
                [vc.view removeFromSuperview];
            }
        }
 
        
        
    }
    if (!find) {
        if (_checkType == CheckScheduleType_ByDay) {
            ScheduleDayController *coachSchduleVC = [ScheduleDayController controllerWithDate:_selectDate];
            [self addChildViewController:coachSchduleVC];
            [_contentScrollView addSubview:coachSchduleVC.view];
            coachSchduleVC.view.frame = _contentScrollView.bounds;
            coachSchduleVC.view.left = kDeviceWidth;
            [self.contentControllers addObject:coachSchduleVC];
        } else {
            ScheduleWeekController *scheduleWeekVC = [ScheduleWeekController controllerWithDate:_selectDate];
            [self addChildViewController:scheduleWeekVC];
            [_contentScrollView addSubview:scheduleWeekVC.view];
            scheduleWeekVC.view.frame = _contentScrollView.bounds;
            scheduleWeekVC.view.left = kDeviceWidth;
            [self.contentControllers addObject:scheduleWeekVC];
        }

    }

}

#pragma mark Action

/**
 选择日期
 */
- (void)choiceDate
{
    WeakSelf(self);
    [YDChoiceDateAlertView showWithDate:_selectDate datePickerMode:UIDatePickerModeDate minDate:nil maxDate:nil comfirmBlock:^(NSDate *date) {
        weakself.selectDate = date;
        [weakself updateContent];
    }];
}

/**
 返回今天
 */
- (void)goTodayBtnClicked
{
    _selectDate = [NSDate date];
    [self updateContent];
}


#pragma mark UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dateList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DateCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([DateCollectionCell class]) forIndexPath:indexPath];
    NSDate *date = _dateList[indexPath.item];
    cell.dateLabel.text = [Toolkit stringFromDate:date formatterString:@"dd"];
    if (_checkType == CheckScheduleType_ByDay) {
        if ([date isSameDay:_selectDate]) {
            cell.dateLabel.backgroundColor = HEXColor(@"#3AA7FF");
            cell.dateLabel.textColor = [UIColor whiteColor];
        } else {
            cell.dateLabel.backgroundColor = [UIColor clearColor];
            if ([date isSameDay:[NSDate date]]) {
                cell.dateLabel.textColor = HEXColor(@"#3AA7FF");
            } else {
                cell.dateLabel.textColor = HEXColor(@"#0E1C29");
            }
        }
    } else {
        cell.dateLabel.backgroundColor = [UIColor clearColor];
        if ([date isSameDay:[NSDate date]]) {
            cell.dateLabel.textColor = HEXColor(@"#3AA7FF");
        } else {
            cell.dateLabel.textColor = HEXColor(@"#0E1C29");
        }
    }
    cell.weekDayLabel.text = [self.dateWeekDayList safeObjectAtIndex:indexPath.item%7];
    
    return cell;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_checkType == CheckScheduleType_ByDay) {
        NSDate *selectDate =_dateList[indexPath.item];
        if (![selectDate isSameDay:_selectDate]) {
            _selectDate = selectDate;
            [self updateContent];
        }
    } else {
        
    }
}


//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
//    return CGSizeMake((kDeviceWidth - 46) / 7,70);
//}

#pragma mark UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _contentScrollView) {
        NSDate *date;
        NSInteger index;
        if (scrollView.contentOffset.x < kDeviceWidth) {
            if (_checkType == CheckScheduleType_ByDay) {
                date = [_selectDate dateBySubtractingDays:1];
            } else {
                date = [_selectDate dateBySubtractingDays:7];
            }
            index = 0;
        } else if (scrollView.contentOffset.x > kDeviceWidth) {
            if (_checkType == CheckScheduleType_ByDay) {
                date = [_selectDate dateByAddingDays:1];
            } else {
                date = [_selectDate dateByAddingDays:7];
            }
            index = 2;
        } else {
            date = _selectDate;
            index = 1;
        }
        BOOL find = NO;
        
        
        for (UIViewController *vc in self.contentControllers) {
            if (_checkType == CheckScheduleType_ByDay) {
                if ([vc isKindOfClass:[ScheduleDayController class]]){
                    ScheduleDayController *coachSchduleVC = (ScheduleDayController *)vc;
                    if ([coachSchduleVC.date isSameDay:date]) {
                        [_contentScrollView addSubview:coachSchduleVC.view];
                        coachSchduleVC.view.left = index * kDeviceWidth;
                        find = YES;
                        break;
                    }
                }
            } else {
                if ([vc isKindOfClass:[ScheduleWeekController class]]){
                    ScheduleWeekController *scheduleWeekVC = (ScheduleWeekController *)vc;
                    if ([[scheduleWeekVC.date getFirstAndLastDayOfThisWeek].firstObject isSameDay:[date getFirstAndLastDayOfThisWeek].firstObject]) {//代表同一周
                        [_contentScrollView addSubview:scheduleWeekVC.view];
                        scheduleWeekVC.view.left = index * kDeviceWidth;
                        find = YES;
                        break;
                    }
                }
            }
            
            
        }
        if (!find) {
            if (_checkType == CheckScheduleType_ByDay) {
                ScheduleDayController *coachSchduleVC = [ScheduleDayController controllerWithDate:date];
                [self addChildViewController:coachSchduleVC];
                [_contentScrollView addSubview:coachSchduleVC.view];
                coachSchduleVC.view.frame = _contentScrollView.bounds;
                coachSchduleVC.view.left = index * kDeviceWidth;
                [self.contentControllers addObject:coachSchduleVC];
            } else {
                ScheduleWeekController *schduleWeekVC = [ScheduleWeekController controllerWithDate:date];
                [self addChildViewController:schduleWeekVC];
                [_contentScrollView addSubview:schduleWeekVC.view];
                schduleWeekVC.view.frame = _contentScrollView.bounds;
                schduleWeekVC.view.left = index * kDeviceWidth;
                [self.contentControllers addObject:schduleWeekVC];
            }
            
        }
        
    }
}
/**
 *  当scrollView停止滚动的时候调用
 */
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == _dateCollectionView) {
        if (scrollView.contentOffset.x < scrollView.frame.size.width / 2) {
            _selectDate = [_selectDate orwardOneWeek];
            [self updateContent];
        } else if (scrollView.contentOffset.x > (scrollView.frame.size.width  + scrollView.frame.size.width / 2)) {
            _selectDate = [_selectDate backwardOneWeek];
            [self updateContent];
        }
    } else if (scrollView == _contentScrollView) {
        if (scrollView.contentOffset.x < scrollView.frame.size.width / 2) {
            if (_checkType == CheckScheduleType_ByDay) {
                _selectDate = [_selectDate dateBySubtractingDays:1];
            } else {
                _selectDate = [_selectDate orwardOneWeek];
            }
            
            [self updateContent];
            
        } else if (scrollView.contentOffset.x > (scrollView.frame.size.width  + scrollView.frame.size.width / 2)) {
            if (_checkType == CheckScheduleType_ByDay) {
                _selectDate = [_selectDate dateByAddingDays:1];
            } else {
                _selectDate = [_selectDate backwardOneWeek];
            }
            
            [self updateContent];
        }
    }

}

#pragma mark YDSwitchDelegate
- (void)choiceIndex:(NSInteger)index
{
    CheckScheduleType newType;
    if (index == 0) {
        newType = CheckScheduleType_ByDay;
    } else {
        newType = CheckScheduleType_ByWeek;
    }
    if (_checkType != newType) {
        _checkType = newType;
        [self updateContent];
    }
}



@end
